﻿using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;

namespace NopSolutions.NopCommerce.BusinessLogic.Infrastructure.Caching
{
    public class NopWebCache : ICacheManager
    {
        private readonly Cache _cache;

        public NopWebCache() {
            _cache = HttpRuntime.Cache;
        }

        #region ICacheManager Members

        public object Get(string key) {
            if (_cache[key] != null) {
                return _cache[key];
            }
            return null;
        }

        public void Add(string key, object obj) {
            Add(key, obj, null);
        }

        public void Add(string key, object obj, CacheDependency cacheDependency) {
            Add(key, obj, cacheDependency, Cache.NoAbsoluteExpiration);
        }

        public void Add(string key, object obj, CacheDependency cacheDependency, DateTime absoluteExpiration) {
            Add(key, obj, cacheDependency, absoluteExpiration, Cache.NoSlidingExpiration);
        }

        public void Add(string key, object obj, CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration) {
            Add(key, obj, cacheDependency, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal);
        }

        public void Add(string key, object obj, CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority cacheItemPriority) {
            Add(key, obj, cacheDependency, absoluteExpiration, slidingExpiration, cacheItemPriority, null);
        }

        public void Add(string key, object obj, CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority cacheItemPriority, CacheItemRemovedCallback onRemoveCallback) {
            if (_cache[key] != null)
                Remove(key);
            _cache.Add(key, obj, cacheDependency, absoluteExpiration, slidingExpiration, cacheItemPriority, onRemoveCallback);
        }

        public void Remove(string key) {
            if (Get(key) != null)
                _cache.Remove(key);
        }

        public void RemoveByPattern(string pattern) {
            IDictionaryEnumerator enumerator = _cache.GetEnumerator();
            Regex regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            while (enumerator.MoveNext()) {
                if (regex.IsMatch(enumerator.Key.ToString())) {
                    _cache.Remove(enumerator.Key.ToString());
                }
            }
        }

        public void Clear() {
            IDictionaryEnumerator enumerator = _cache.GetEnumerator();
            while (enumerator.MoveNext()) {
                _cache.Remove(enumerator.Key.ToString());
            }
        }

        #endregion
    }
}
